package com.ytf.dogbox.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicYuvToRGB;
import android.renderscript.Type;

/**
 * Created by caydencui on 2018/12/7.
 * 高效率的nv21转bitmap
 */
public class NV21ToBitmap {

  private RenderScript rs;
  private ScriptIntrinsicYuvToRGB yuvToRgbIntrinsic;
  private Type.Builder yuvType, rgbaType;
  private Allocation in, out;
  private Context context;
  public NV21ToBitmap(Context context) {
//      this.context=context;
       rs = RenderScript.create(context);
       yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
  }
  //生成图片
  public Bitmap nv21ToBitmap(byte[] nv21, int width, int height){
//      Log.e("tiwolf", "nv21ToBitmap--: 进来了一个新图片");
//      rs = RenderScript.create(context);
//      yuvToRgbIntrinsic = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs));
      Bitmap bmpout=null;
      Type yuv=null;
      Type rgba=null;
      try{
//          if (yuvType == null){
//              Log.e("tiwolf", "receiveWork: 图片nv21ToBitmap: yuvType为null");
              yuvType = new Type.Builder(rs, Element.U8(rs)).setX(nv21.length);
              yuv=yuvType.create();
              in = Allocation.createTyped(rs, yuv, Allocation.USAGE_SCRIPT);
              rgbaType = new Type.Builder(rs, Element.RGBA_8888(rs)).setX(width).setY(height);
              rgba=rgbaType.create();
              out = Allocation.createTyped(rs, rgba, Allocation.USAGE_SCRIPT);
//          }
          in.copyFrom(nv21);
          yuvToRgbIntrinsic.setInput(in);
          yuvToRgbIntrinsic.forEach(out);
          bmpout = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
          out.copyTo(bmpout);
//          in=null;
//          out=null;
//          nv21=null;
      }catch (Exception e){
          e.printStackTrace();
//          in=null;
//          out=null;
      }finally {
          if (out!=null){
              out.destroy();
          }
          if (in!=null){
              in.destroy();
          }
          if (yuv!=null){
              yuv.destroy();        //TODO 2021.10.09 这个没设置导致内存泄漏
          }
          if (rgba!=null){
              rgba.destroy();       //TODO 2021.10.09 这个没设置导致内存泄漏
          }

//          rs.destroy();
//          yuvToRgbIntrinsic.destroy();
          out=null;
          in=null;
          rgba=null;
          yuv=null;
      }
//      Log.e("tiwolf", "nv21ToBitmap--: 我已经转换结束了");
      return bmpout;
  }

}
